package net;

import java.net.URLDecoder;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import com.component.PropUtil;
import com.component.Util;
import com.component.code.Constant;
import com.component.code.TishiManager;
import com.component.encrypt.DecryptUtil;
import com.component.mode.ReturnMsg;
import com.data.cache.DeskPlayerServiceCache;
import com.data.spring.BeanFactory;
import com.data.third.DataService;
import com.dictionary.DictionaryTabel;
import com.game.model.BasePlayer;
import com.game.model.PlayerInfoLocal;
import com.game.monitor.DataMonitoredService;
import com.game.serivce.ConfigService;
import com.game.serivce.DeskPlayerService;
import com.game.serivce.GameRoomService;

public class ServerHandler extends IoHandlerAdapter {
	private Logger logger = Logger.getLogger(ServerHandler.class.getName());
	public static GameRoomService[] gameRoomServices;
	public DataMonitoredService dataMonitoredService;

	public ServerHandler() {
		/*
		 * ConfigService.getInstance().readAllConfig_noBD(); gameRoomServices =
		 * new GameRoomService[1]; gameRoomServices[0] = new GameRoomService(new
		 * ConfigRoom());
		 */
		// BeanFactory.getBeanFactory();
		ConfigService.getInstance().readAllConfig();
		gameRoomServices = new GameRoomService[ConfigService.getInstance()
				.getConfigRoomServices().size()];
		for (int i = 0; i < ConfigService.getInstance().getConfigRoomServices()
				.size(); i++) {
			if (ConfigService.getInstance().getConfigRoomServices().get(i).isOpen == 1) {
				gameRoomServices[i] = new GameRoomService(ConfigService
						.getInstance().getConfigRoomServices().get(i));
				// gameRoomServices[i] = new GameRoomService(i);
			} else {
				gameRoomServices[i] = null;
			}
		}
		dataMonitoredService = new DataMonitoredService(gameRoomServices);
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		try {
			if (session.containsAttribute("playerId")) {
				long playerId = (long) session.getAttribute("playerId");
				DeskPlayerService dps = DeskPlayerServiceCache.SessionMap
						.get(playerId);
				if (dps != null) {
					try {
						gameRoomServices[dps.playerService.deskPlayer.getRoomNum()].waitJoinPlayers
								.remove(dps);
						if (dps.playerService.deskPlayer.getDeskNum() > -1) {
							gameRoomServices[dps.playerService.deskPlayer.getRoomNum()].roomDeskServices[dps.playerService.deskPlayer
									.getDeskNum()].leaveDesk(dps);
						} else {
							logger.warn("deskNum : -1");
							gameRoomServices[dps.playerService.deskPlayer.getRoomNum()]
									.leaveRoom(dps);
						}
					} catch (Exception e) {
						logger.error(e.getMessage(), e);
					}
					dps = null;
				} else {
					logger.warn("no player cache : " + playerId);
				}
			} else {
				logger.warn("no attribute : playerId");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		super.sessionClosed(session);
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		cause.printStackTrace();
		sessionClosed(session);
	}

	// 消息接收
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		String str = null;
		// 心跳
		try {
			str = new String((byte[]) message);
			str = URLDecoder.decode(str, "UTF-8");

			if (str.equals("-100@")) {
				session.write("-100@@&");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			session.close(true);
			return;
		}
		if (str.length() == 0) {
			return;
		}

		String[] res = str.split("@");

		if (Integer.valueOf(res[0]) < 300)
			logger.info("接收请求信息：" + str);

		switch (Integer.valueOf(res[0])) {
		case SocketEnum.CONN:
			conn(session, res[1]);
			break;
		case SocketEnum.RECONN:
			reconn_Receive(session);
			break;
		case SocketEnum.JOINROOM:
			joinRoom_Receive(session, res[1]);
			break;
		// case SocketEnum.BET:
		// bet_Receive(session, res[1]);
		// break;
		case SocketEnum.BEGIN:
			begin(session, res[1]);
			break;
		// case SocketEnum.CLEAR:
		// clear_Receive(session);
		// break;
		// case SocketEnum.REPEAT:
		// repeat_Receive(session);
		// break;
		// case SocketEnum.HISTORY:
		// history_Receive(session);
		// break;
		case SocketEnum.GETPLAYERINFO:
			playerList_Receive(session);
			break;
		// ------------------------监控工具----------------------
		case SocketEnum.DataMonitored_CONN:
			dataMonitoredService.dataMonitored_CONN(session);
			break;
		case SocketEnum.DataMonitored_GETROOMLIST:
			dataMonitoredService.dataMonitored_ROOMLIST(session);
			break;
		case SocketEnum.DataMonitored_GETDESKLIST:
			dataMonitoredService.dataMonitored_GETDESKLIST(session, res[1]);
			break;
		case SocketEnum.DataMonitored_GETDESKINFO:
			dataMonitoredService.dataMonitored_GETDESKINFO(session, res[1]);
			break;
		case SocketEnum.DataMonitored_GETPLAYERINFO:
			dataMonitoredService.dataMonitored_GETPLAYERINFO(session, res[1]);
			break;
		case SocketEnum.DataMonitored_GETCONFIG:
			dataMonitoredService.dataMonitored_GETCONFIG(session, res[1]);
			break;
		case SocketEnum.DataMonitored_UPDATACONFIG:
			dataMonitoredService.DataMonitored_UPDATACONFIG(session, res[1]);
			break;
		case SocketEnum.DataMonitored_CLOSEDESK:
			dataMonitoredService.dataMonitored_CLOSEDESK(session, res[1]);
			break;
		case SocketEnum.DataMonitored_STARTDESK:
			dataMonitoredService.dataMonitored_STARTDESK(session, res[1]);
			break;
		case SocketEnum.DataMonitored_SENDGUANGBO:
			dataMonitoredService.dataMonitored_SENDGUANGBO(session, res[1]);
			break;
		case SocketEnum.DataMonitored_READDB:
			dataMonitoredService.dataMonitored_READDB(session);
			break;
		case SocketEnum.DataMonitored_GETWAITINFO:
			dataMonitoredService.dataMonitored_GETWAITINFO(session, res[1]);
			break;

		default:
			break;
		}
	}

	private void conn(IoSession session, String str) {
		try {
			JSONObject json = DecryptUtil.getValidData(JSONObject
					.fromObject(str.replaceAll(" ", "+")));
			long playerId = json.getLong("playerID");
			String token = json.getString("token");
			String p = json.getString("P");
			int platformId = json.getInt("platformId");

			// 加载进度条
			// session.write(SocketEnum.loadingI + "@" + (10 + (int)
			// (Math.random() * 5)) + "@&");
			ReturnMsg rmsg = DataService.checkToken(playerId, token, p,
					platformId);
			rmsg.setState(1);
			if (rmsg.getState() == 1) {

				session.setAttribute("playerId", playerId);
				// session.setAttribute("joinType",
				// DictionaryTabel.JoinType_PlayerJion);

				// 是否有重连记录
				rmsg = DataService.roomReConQuery(playerId);
				if (rmsg.getResult().size() > 0) {
					JSONObject jsonObject = rmsg.getResult().getJSONObject(0);
					int gameId = jsonObject.getInt("gameID");
					if (gameId == Integer.parseInt(PropUtil
							.getProperty("gameId"))) {
						int roomId = jsonObject.getInt("roomID");
						// DataService.resetTime(playerId, gameId, roomId, 2);
					}
				}
				// TODO 判断是否重复登录
				if (DeskPlayerServiceCache.SessionMap.containsKey(playerId)) {
					DeskPlayerService dps = DeskPlayerServiceCache.SessionMap
							.get(playerId);
					dps.playerService.sendMessage(SocketEnum.infoI,
							TishiManager.Tishi_T_SecondLogin);
					dps.playerService.getSession().close(false);
					// oldDps.sendMessage(SocketEnum.closeConnI,"");
				}
				session.write(SocketEnum.connI + "@@&");
			} else {
				// TODO 加载进度条
				session.write(SocketEnum.infoI + "@" + rmsg.getInfo() + "@&");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	private void joinRoom_Receive(IoSession session, String str) {
		String[] ss = str.split(",", -1);
		long playerId = Long.parseLong(ss[0]);
		int roomId = Integer.valueOf(ss[1]);
		System.out.println("playerId" + playerId);
		System.out.println("roomId" + roomId);
		// int roomId = Integer.parseInt(str);
		// long playerId = (long) session.getAttribute("playerId");
		// 获取玩家信息及背包信息
		ReturnMsg rmsg = DataService.getPlayeBaseInfo(playerId);
		System.out.println("获取玩家信息"+rmsg.getResult().getJSONObject(0));
		try {
			DeskPlayerService dps = new DeskPlayerService(rmsg.getResult().getJSONObject(0));
			rmsg = DataService.getPlayerBagInfo(playerId);
			dps.playerService.deskPlayer.setBagInfo(rmsg.getResult().getJSONObject(0));
			dps.playerService.deskPlayer.setGameNum(ConfigService.getInstance().configRooms
					.get(roomId).getId().getGameId());
			dps.playerService.deskPlayer.setRoomNum(ConfigService.getInstance().configRooms
					.get(roomId).getId().getRoomId());
			dps.playerService.setSession(session);
			// 加载进度条
			// dps.sendMessage(SocketEnum.loadingI, (40 + (int) (Math.random() *
			// 5)) + "");
			// 开始进入房间
			
			gameRoomServices[dps.playerService.deskPlayer.getRoomNum()].joinRoom(dps);
			DeskPlayerServiceCache.SessionMap.put(playerId, dps);

		} catch (Exception e) {
			session.write(SocketEnum.infoI + "@"
					+ TishiManager.Tishi_T_GetPlayerInfo_Fail + "@&");
			logger.error(e.getMessage(), e);
		}
	}

	private void begin(IoSession session, String str) {
		System.out.println("开始:"+ str);
		long playerId = (long) session.getAttribute("playerId");
		DeskPlayerService dps = DeskPlayerServiceCache.SessionMap.get(playerId);
		System.out.println("-------->");
		System.out.println(dps.playerService.deskPlayer.getRoomNum());
		System.out.println(dps.playerService.deskPlayer.getDeskNum());
		System.out.println(dps.playerService.deskPlayer.getSeatNum());
		try {
//			if (dps.deskPlayer.getState() == DictionaryTabel.player_operate){
			gameRoomServices[dps.playerService.deskPlayer.getRoomNum()].roomDeskServices[dps.playerService.deskPlayer
					.getDeskNum()].deskPlayerServices[dps.playerService.deskPlayer
					.getSeatNum()].begin(str);
//			}else {
//				session.write(SocketEnum.infoI + "@" + Constant.Tishi_Connect_Fail
//						+ "@&");
//			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("commonExceotion", e);
			session.write(SocketEnum.infoI + "@" + Constant.Tishi_Connect_Fail
					+ "@&");
		}
	}

	private void reconn_Receive(IoSession session) {
		if (session.containsAttribute("playerId")) {
			long playerId = (long) session.getAttribute("playerId");
			if (DeskPlayerServiceCache.SessionMap.containsKey(playerId)) {
				DeskPlayerService dps = DeskPlayerServiceCache.SessionMap
						.get(playerId);
				if (dps.playerService.getSession() != null) {
					dps.playerService.sendMessage(SocketEnum.reJoinRoom, "");
					gameRoomServices[dps.playerService.deskPlayer.getRoomNum()]
							.reJoinRoom(dps);
					return;
				}
			}
		}
		session.write(SocketEnum.infoI + "@" + TishiManager.Tishi_T_SecondLogin
				+ "@&");
	}

	// private void bet_Receive(IoSession session, String str) {
	// long playerId = (long) session.getAttribute("playerId");
	// DeskPlayerService dps = DeskPlayerServiceCache.SessionMap.get(playerId);
	// if (dps.deskPlayer.getState() == DictionaryTabel.player_xiazhu) {
	// String[] strs = str.split(",");
	// int sub = Integer.parseInt(strs[0]);
	// int betChip = Integer.parseInt(strs[1]);
	// dps.operate_Bet(sub, betChip);
	// } else {
	// session.write(SocketEnum.infoI + "@" +
	// TishiManager.Tishi_F_Game_OutBetTime + "@&");
	// }
	// }

	// private void clear_Receive(IoSession session) {
	// long playerId = (long) session.getAttribute("playerId");
	// DeskPlayerService dps = DeskPlayerServiceCache.SessionMap.get(playerId);
	// if (dps.deskPlayer.getState() == DictionaryTabel.player_xiazhu)
	// dps.operate_Clear();
	// else
	// session.write(SocketEnum.infoI + "@" +
	// TishiManager.Tishi_F_Game_OutBetTime + "@&");
	// }

	// private void repeat_Receive(IoSession session) {
	// long playerId = (long) session.getAttribute("playerId");
	// DeskPlayerService dps = DeskPlayerServiceCache.SessionMap.get(playerId);
	// if (dps.deskPlayer.getState() == DictionaryTabel.player_xiazhu) {
	// if (dps.deskPlayer.getBetInfo().size() == 0) {
	// dps.operate_Repeat();
	// }/* else {
	// session.write(SocketEnum.infoI + "@" +
	// TishiManager.Tishi_F_Game_RepeatBet + "@&");
	// }*/
	// } else {
	// session.write(SocketEnum.infoI + "@" +
	// TishiManager.Tishi_F_Game_OutBetTime + "@&");
	// }
	// }

	// private void history_Receive(IoSession session) {
	// /*long playerId = (long) session.getAttribute("playerId");
	// DeskPlayerService dps = DeskPlayerServiceCache.SessionMap.get(playerId);
	// dps.operate_History();*/
	// }

	private void playerList_Receive(IoSession session) {

		try {
			String roomId = session.getAttribute("roomNum") + "";
			gameRoomServices[Integer.valueOf(roomId)].getPlayerInfo(session);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("commonExceotion", e);
			session.write(SocketEnum.infoI + "@" + Constant.Tishi_Connect_Fail
					+ "@&");
		}

		/*
		 * long playerId = (long) session.getAttribute("playerId");
		 * DeskPlayerService dps =
		 * DeskPlayerServiceCache.SessionMap.get(playerId);
		 * dps.operate_PlayerList();
		 */}
}
